<template>
	<view class="refund-detail-container">
		<!-- 状态卡片 -->
		<view class="status-card">
			<view class="status-info">
				<text class="status-text" :class="getStatusClass(refundDetail.requestStatus)">
					{{getStatusText(refundDetail.requestStatus)}}
				</text>
				<text class="status-desc">{{getStatusDesc(refundDetail.requestStatus)}}</text>
			</view>
		</view>

		<!-- 退款信息 -->
		<view class="info-section">
			<view class="section-title">退款信息</view>
			<view class="info-item">
				<text class="label">申请编号</text>
				<text class="value">{{refundDetail.rrId}}</text>
			</view>
			<view class="info-item">
				<text class="label">订单号</text>
				<text class="value">{{refundDetail.orderId}}</text>
			</view>
			<view class="info-item">
				<text class="label">申请时间</text>
				<text class="value">{{formatTime(refundDetail.requestTime)}}</text>
			</view>
			<view class="info-item">
				<text class="label">申请金额</text>
				<text class="value amount">¥{{refundDetail.requestAmount}}</text>
			</view>
			<view class="info-item" v-if="refundDetail.actualAmount !== null">
				<text class="label">实际退款</text>
				<text class="value amount">¥{{refundDetail.actualAmount}}</text>
			</view>
		</view>

		<!-- 订单菜品信息 -->
		<view class="info-section" v-if="refundDetail.orderItems && refundDetail.orderItems.length">
			<view class="section-title" style="display:flex;align-items:center;justify-content:space-between;">
				<text>订单菜品信息</text>
				<text class="toggle-btn" @click="orderItemsExpanded = !orderItemsExpanded">
					{{ orderItemsExpanded ? '收起' : '展开' }}
				</text>
			</view>
			<view v-if="orderItemsExpanded">
				<view v-for="item in refundDetail.orderItems" :key="item.dish.dishId" class="order-item">
					<image :src="`https://rsl-plus.oss-rg-china-mainland.aliyuncs.com/${item.dish.dishImage}`" class="dish-image" mode="aspectFill" />
					<view class="dish-info">
						<text class="dish-name">{{item.dish.dishName}}</text>
						<text class="dish-qty">x{{item.orderItem.quantity}}</text>
					</view>
					<text class="dish-price">¥{{item.dish.price}}</text>
				</view>
			</view>
		</view>

		<!-- 退款原因 -->
		<view class="info-section">
			<view class="section-title">退款原因</view>
			<view class="reason-content">
				<text class="reason-text">{{refundDetail.reason}}</text>
				<text class="reason-desc" v-if="refundDetail.refundDesc">{{refundDetail.refundDesc}}</text>
			</view>
		</view>

		<!-- 退款图片 -->
		<view class="info-section" v-if="refundDetail.imagePath && refundDetail.imagePath.length > 0">
			<view class="section-title">相关图片</view>
			<view class="image-list">
				<image 
					v-for="(img, index) in refundDetail.imagePath" 
					:key="img"
					:src="`https://rsl-plus.oss-rg-china-mainland.aliyuncs.com/${img}`" 
					class="refund-image"
					@click="previewImage(index)"
					mode="aspectFill"
				/>
			</view>
		</view>

		<!-- 客户信息 -->
		<view class="info-section">
			<view class="section-title">客户信息</view>
			<view class="info-item">
				<text class="label">客户姓名</text>
				<text class="value">{{refundDetail.customerFullName}}</text>
			</view>
			<view class="info-item">
				<text class="label">联系电话</text>
				<text class="value">{{formatPhone(refundDetail.phone)}}</text>
			</view>
		</view>

		<!-- 拒绝原因 -->
		<view class="info-section" v-if="refundDetail.refuseReason">
			<view class="section-title">拒绝原因</view>
			<view class="refuse-content">
				<text class="refuse-text">{{refundDetail.refuseReason}}</text>
				<text class="refuse-time" v-if="refundDetail.operateTime">
					处理时间：{{formatTime(refundDetail.operateTime)}}
				</text>
			</view>
		</view>

		<!-- 操作按钮 -->
		<view class="action-section" v-if="refundDetail.requestStatus === 0">
			<button class="action-btn reject" @click="handleRefund('reject')">拒绝退款</button>
			<button class="action-btn approve" @click="handleRefund('approve')">同意退款</button>
		</view>
	</view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { refundApi,orderApi } from '../../utils/api.js'

// 响应式数据
const refundDetail = reactive({
	rrId: null,
	orderId: '',
	requestTime: '',
	requestStatus: 0,
	requestAmount: 0,
	actualAmount: null,
	reason: '',
	refundDesc: '',
	refuseReason: null,
	operateTime: null,
	customerFullName: '',
	phone: '',
	imagePath: [],
	orderItems: [],
	uid:null
})

const orderItemsExpanded = ref(false) // 控制订单菜品区块展开/收起

// 测试数据
const mockRefundData = {}

// 方法
const getStatusText = (status) => {
	const statusMap = {
		0: '待处理',
		1: '已同意',
		2: '已拒绝'
	}
	return statusMap[status] || '未知状态'
}

const getStatusClass = (status) => {
	const classMap = {
		0: 'pending',
		1: 'approved',
		2: 'rejected'
	}
	return classMap[status] || 'pending'
}

const getStatusDesc = (status) => {
	const descMap = {
		0: '商家正在处理您的退款申请',
		1: '您的退款申请已通过，退款将原路返回',
		2: '您的退款申请被拒绝，如有疑问请联系客服 '
	}
	return descMap[status] || ''
}

const formatTime = (timeStr) => {
	if (!timeStr) return ''
	
	// 将 "yyyy-MM-dd HH:mm:ss" 格式转换为 "yyyy/MM/dd HH:mm:ss" 格式以兼容iOS
	const formattedTimeStr = timeStr.replace(/-/g, '/')
	const date = new Date(formattedTimeStr)
	
	// 检查日期是否有效
	if (isNaN(date.getTime())) {
		console.error('无效的日期格式:', timeStr)
		return timeStr // 返回原始字符串
	}
	
	const year = date.getFullYear()
	const month = String(date.getMonth() + 1).padStart(2, '0')
	const day = String(date.getDate()).padStart(2, '0')
	const hours = String(date.getHours()).padStart(2, '0')
	const minutes = String(date.getMinutes()).padStart(2, '0')
	return `${year}-${month}-${day} ${hours}:${minutes}`
}

const previewImage = (index) => {
	const urls = refundDetail.imagePath.map(img => {
		// 如果是完整路径直接返回，否则拼接静态目录
		return img.startsWith('http') ? img : '/static/' + img
	})
	uni.previewImage({
		current: index,
		urls: urls
	})
}

const handleRefund = (action) => {
	if (action === 'reject') {
		// 拒绝退款时弹出输入框
		uni.showModal({
			title: '拒绝退款',
			content: '',
			editable: true,
			placeholderText: '请输入拒绝退款的原因',
			showCancel: true,
			cancelText: '取消',
			confirmText: '确认拒绝',
			success: (res) => {
				if (res.confirm) {
					const refuseReason = res.content.trim()
					if (!refuseReason) {
						uni.showToast({
							title: '请输入拒绝原因',
							icon: 'none'
						})
						return
					}
					refundDetail.refuseReason = refuseReason
					refundDetail.requestStatus = 2
					processRefuse(refundDetail)
				}
			}
		})
	} else {
		// 同意退款时直接确认
		const actionText = action === 'approve' ? '同意' : '拒绝'
		uni.showModal({
			title: '确认操作',
			content: `确定要${actionText}该退款申请吗？`,
			success: (res) => {
				if (res.confirm) {
					refundDetail.actualAmount = refundDetail.actualAmount || refundDetail.requestAmount
					refundDetail.requestStatus = 1
					processRefund(refundDetail)
				}
			}
		})
	}
}

//拒绝退款处理
const processRefuse = async (refundDetail) => {
	const response = await refundApi.updateRefund(refundDetail)
	console.log(response)
	
}

const processRefund = async (refundDetail) => {
	try {
		const payWay = refundDetail.payWay === 1 ? 'memberCard' : 'wechat'
		const refundRequest = {
			rrId: refundDetail.rrId,
			requestStatus: refundDetail.requestStatus,
			actualAmount: refundDetail.actualAmount,
			uId:refundDetail.uid
		}
		const data = {
			refundRequest,
			payWay
		}
		// 调用退款处理接口
		const response = await refundApi.processRefund(data)
		uni.showToast({
			title: `退款成功`,
			icon: 'success'
		})
		
	} catch (error) {
		console.error('处理退款失败:', error)
		uni.showToast({
			title: '操作失败',
			icon: 'error'
		})
	}
}

// 获取退款详情
const getRefundDetail = async (rrId) => {
	try {
		// 调用接口获取退款详情
		const response = await refundApi.getRefundDTOByRefundId(rrId)
		console.log("response:",response)
		Object.assign(refundDetail, response.data)
		// 预留：获取订单菜品信息
		if (refundDetail.orderId) {
			getOrderItems(refundDetail.orderId)
		}
	} catch (error) {
		console.error('获取退款详情失败:', error)
		// 使用模拟数据
		Object.assign(refundDetail, mockRefundData)
		getOrderItems(mockRefundData.orderId)
	}
}

// 格式化手机号，中间四位用*号
const formatPhone = (phone) => {
	if (!phone) return ''
	return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

// 预留接口：根据orderId获取订单菜品信息
const getOrderItems = async (orderId) => {
	// 实际开发中应调用后端接口获取
	const response = await orderApi.getOrderItems(orderId)
	console.log(response)
	refundDetail.orderItems = response.data
}

// 生命周期
onMounted(() => {
	const pages = getCurrentPages()
	const currentPage = pages[pages.length - 1]
	const rrId = currentPage.options.rrId
	
	if (rrId) {
		getRefundDetail(rrId)
	}
})
</script>

<style>
.refund-detail-container {
	min-height: 100vh;
	background: linear-gradient(135deg, #f8fafc 0%, #e9eaf3 100%);
	padding-bottom: 120rpx;
}

.status-card {
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	padding: 48rpx 30rpx 36rpx 30rpx;
	color: #fff;
	border-radius: 0 0 24rpx 24rpx;
	box-shadow: 0 6rpx 24rpx rgba(102,126,234,0.12);
	margin-bottom: 24rpx;
}

.status-info {
	text-align: center;
}

.status-text {
	font-size: 40rpx;
	font-weight: bold;
	display: block;
	margin-bottom: 12rpx;
	letter-spacing: 2rpx;
}

.status-desc {
	font-size: 28rpx;
	opacity: 0.92;
}

.info-section {
	background: #fff;
	margin: 24rpx 20rpx 0 20rpx;
	border-radius: 18rpx;
	padding: 32rpx 28rpx 24rpx 28rpx;
	box-shadow: 0 4rpx 16rpx rgba(102,126,234,0.06);
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 22rpx;
	border-left: 8rpx solid #667eea;
	padding-left: 18rpx;
	letter-spacing: 1rpx;
}

.info-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 18rpx;
}

.info-item:last-child {
	margin-bottom: 0;
}

.label {
	font-size: 28rpx;
	color: #888;
}

.value {
	font-size: 28rpx;
	color: #222;
	font-weight: 500;
}

.value.amount {
	color: #C70209;
	font-weight: bold;
	font-size: 30rpx;
}

.reason-content {
	background: #f6f8fa;
	padding: 22rpx;
	border-radius: 10rpx;
	margin-bottom: 6rpx;
}

.reason-text {
	font-size: 28rpx;
	color: #333;
	line-height: 1.5;
	display: block;
	margin-bottom: 10rpx;
}

.reason-desc {
	font-size: 26rpx;
	color: #888;
	line-height: 1.5;
}

.image-list {
	display: flex;
	flex-wrap: wrap;
	gap: 18rpx;
}

.refund-image {
	width: 180rpx;
	height: 180rpx;
	border-radius: 12rpx;
	box-shadow: 0 2rpx 8rpx rgba(102,126,234,0.10);
	transition: transform 0.2s;
}
.refund-image:active {
	transform: scale(1.06);
}

.refuse-content {
	background: #fff1f0;
	padding: 20rpx;
	border-radius: 10rpx;
	border-left: 4rpx solid #ff4d4f;
}

.refuse-text {
	font-size: 28rpx;
	color: #333;
	line-height: 1.5;
	display: block;
	margin-bottom: 10rpx;
}

.refuse-time {
	font-size: 24rpx;
	color: #999;
}

.order-item {
	display: flex;
	align-items: center;
	margin-bottom: 14rpx;
	background: #f7f8fa;
	border-radius: 10rpx;
	padding: 10rpx 14rpx;
	box-shadow: 0 2rpx 8rpx rgba(102,126,234,0.04);
}

.dish-image {
	width: 72rpx;
	height: 72rpx;
	border-radius: 8rpx;
	margin-right: 14rpx;
	box-shadow: 0 2rpx 8rpx rgba(102,126,234,0.10);
}

.dish-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: center;
}

.dish-name {
	font-size: 28rpx;
	color: #333;
	font-weight: 500;
}

.dish-qty {
	font-size: 24rpx;
	color: #999;
	margin-top: 2rpx;
}

.dish-desc {
	font-size: 24rpx;
	color: #aaa;
	margin-top: 4rpx;
	line-height: 1.4;
	word-break: break-all;
}

.dish-price {
	font-size: 28rpx;
	color: #C70209;
	font-weight: bold;
	margin-left: 12rpx;
	min-width: 80rpx;
	text-align: right;
}

.action-section {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background: #fff;
	padding: 24rpx 20rpx;
	border-top: 1rpx solid #f0f0f0;
	display: flex;
	gap: 24rpx;
	box-shadow: 0 -2rpx 12rpx rgba(102,126,234,0.06);
}

.action-btn {
	flex: 1;
	height: 84rpx;
	line-height: 84rpx;
	border-radius: 44rpx;
	font-size: 30rpx;
	border: none;
	font-weight: bold;
	box-shadow: 0 2rpx 8rpx rgba(102,126,234,0.10);
	transition: background 0.2s;
}

.action-btn.reject {
	background: #f5f5f5;
	color: #888;
}

.action-btn.approve {
	background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
	color: #fff;
}

.status-text.pending {
	color: #faad14;
}

.status-text.approved {
	color: #52c41a;
}

.status-text.rejected {
	color: #ff4d4f;
}

.toggle-btn {
	font-size: 26rpx;
	color: #667eea;
	padding: 0 8rpx;
	cursor: pointer;
	user-select: none;
}
</style>
